let poiLocation;
let poiLngLat;
let dragLocation;
window.init = function() {
    initAMapUI();
    let lng = $("#longitude");
    let lat = $("#latitude");
    let dragAddress = $("#dragAddress");
    let nearestJunction = $("#nearestJunction");
    let nearestRoad = $("#nearestRoad");
    AMapUI.loadUI(['misc/PositionPicker'], function (PositionPicker) {
        let map = new AMap.Map('container', {
            viewMode: '2D',
            zoom: 11,
        });
        if (location.href.indexOf('&guide=1') !== -1) {
            map.setStatus({scrollWheel: false})
        }

        map.setStatus({scrollWheel: true});
        map.plugin(["AMap.ToolBar", "AMap.Autocomplete", "AMap.PlaceSearch","AMap.CitySearch"], function () {



            //自动补全搜索信息
            let autoOptions = {
                city: '',
                citylimit: true,

                input: "tipInput"
            }
            map.addControl(new AMap.ToolBar({
                position: "LT",
                noIpLocate: true,
                liteStyle: false,
                autoPosition: true
            }));
            // map.addControl(toolBar)

            let autoComplete = new AMap.Autocomplete(autoOptions);
            let placeSearch = new AMap.PlaceSearch({
                citilimit:true,
                type:"购物服务|餐饮服务",
                panel:'result',
                pageSize: 5,
                pageIndex: 1,
                autoFitView: true,
                map: map
            })

            //注册监听事件
            autoComplete.on('select', select);
            function select(e) {
                placeSearch.search(e.poi.name,function (status,result) {

                })
            }
            //POI结果标记点击监听
            placeSearch.on("markerClick",function (e) {
                lng.val(e.data.location.lng);
                lat.val(e.data.location.lat);
                poiLocation = e.data.address;
                // console.log(e.data.location.lng +',' + e.data.location.lat);
                // console.log(e.data.address);
            });
            //POI结果列表点击监听
            placeSearch.on("listElementClick",function (e) {
                lng.val(e.data.location.lng);
                lat.val(e.data.location.lat);
                poiLocation = e.data.address;
                // console.log(e.data.location.lng +',' + e.data.location.lat);
                // console.log(e.data.address);
            });

            $("#img-show").on('click',function () {
                layer.open({
                    type:2,
                    content: $("#img-show").attr("src"),
                    area:['50%','80%']
                })
            });

            //IP定位（城市级）
            function getCurrentCity() {
                let citySearch = new AMap.CitySearch();
                citySearch.getLocalCity(function (status, result) {
                    if (status === 'complete' && result.info === 'OK') {
                        if (result && result.city && result.bounds) {
                            let cityinfo = result.city;
                            let citybounds = result.bounds;
                            //限定搜索城市
                            autoComplete.setCity(cityinfo);
                            placeSearch.setCity(cityinfo);
                            //地图显示当前城市
                            map.setBounds(citybounds);
                            map.setZoom(15)
                        }
                    } else {
                        // console.log(result.city)
                    }
                })
            }

            getCurrentCity();

            //拖拽定位
            let positionPicker = new PositionPicker({
                mode: 'dragMap',
                map: map
            });
            positionPicker.on('success', function (positionResult) {
                //经纬度
                let lngNum = positionResult.position.lng;
                let latNum = positionResult.position.lat;
                // let lnglat = [lngNum,latNum];
                //地址
                let address = positionResult.address;
                //最近的路口
                let nearJunction = positionResult.nearestJunction;
                //最近的街道
                let nearRoad = positionResult.nearestRoad;
                lng.val(lngNum);
                lat.val(latNum);
                dragAddress.empty();
                nearestJunction.empty();
                nearestRoad.empty();
                dragAddress.append(address);
                nearestJunction.append(nearJunction);
                nearestRoad.append(nearRoad);
                // console.log(lngNum+","+latNum);
                // console.log(positionResult.address);
                dragLocation = positionResult.address;

            });
            positionPicker.start();
        });

    })
};








layui.use(['form', 'upload','layer'], function () {
    let $ = layui.jquery
        , upload = layui.upload,
        layer = layui.layer,
        form = layui.form;

    let index;
    $("#chooseAddress").on('click',function () {
        mapModel();
    });
    $("#addressAccess").on('click',function () {
        closeAddressModel(index);
    });

    form.on('submit(updateBtn)',function () {
        // console.log("test click event");
        //店铺信息
        let name = $("input[name='shopName']").val();
        let address = $("input[name='shopAddress']").val();
        let licenseImg = $("#licenseUrl").val();
        let license = $("input[name='credit']").val();
        let id = $("input[name='shopId']").val();
        let aid = $("input[name='adminId']").val();
        let latitude = $("#latitude").val();
        let longitude = $("#longitude").val();
        let shop = {'id':id,'name':name,'aId':aid,'address':address,'latitude':latitude,'longitude':longitude,'license':license,'licenseImg':licenseImg};
        //管理员信息（商铺）
        let username = $("input[name='username']").val();
        let json = {'shop':shop,'username':username};
        // console.log(JSON.stringify(json));
        $.ajax({
            url:"/editShopInfo",
            method: "post",
            charset: "UTF-8",
            dataType: "json",
            cache: false,
            contentType: "application/json;charset=utf-8;",
            data: JSON.stringify(json),
            success:function (res) {
                // console.log(res)
                if (res.data == "1"){
                    alert('修改数据成功！')
                    location.reload();
                }
            }
        })
    });

    function mapModel() {
        index = layer.open({
            type: 1,
            anim: 4,
            shade: 0,
            area: ['800px', '400px'],
            title: '选择地址',
            shadeClose: false,
            zIndex:1,
            offset:'lt',
            content: $('#selectAddressModel')
        });
        // layer.tips('定位时POI搜索定位获取到的地址优先级大于拖拽定位','#addressAccess')
    }

    function closeAddressModel(index) {
        layer.confirm('是否确认更新地址？如确认更新则请选择要使用的地址信息。注意：如检测到并未选择搜索定位地址则默认使用拖拽定位地址。',{
            icon:3,
            title:"提示",
            btn:['搜索定位地址','拖拽定位地址','取消'],
            //关闭按钮回调
            cancel :function () {
                $("input[name='shopAddress']").val("");
                layer.close(layer.index);
                // layer.close(index);
            },
            //确定回调
            btn1:function () {
                //判断poi定位是否存在地址，如果有则使用poi地址，反之使用拖拽定位地址
                if (poiLocation != null){
                    $("input[name='shopAddress']").val(poiLocation);
                }else {
                    $("input[name='shopAddress']").val(dragLocation);
                }

                layer.close(layer.index);
                layer.close(index);
            },
            //使用拖拽定位地址
            btn2:function () {
                $("input[name='shopAddress']").val(dragLocation);
                layer.close(layer.index);
                layer.close(index);

            },
            // btn3:function () {
            //     $("input[name='shopAddress']").val("");
            //     layer.close(layer.index);
            //     layer.close(index);
            // }
        });
    }
    // //普通图片上传
    let uploadInst = upload.render({
        elem: '#uploadLicense'
        , url: '/uploadLicense' //改成您自己的上传接口
        ,size:10485760 //10M
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#img-show').attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.code > 0) {
                return layer.msg('上传失败');
            }
            //上传成功
            $("#licenseUrl").val(res.data);
        }
        , error: function () {
            //演示失败状态，并实现重传
            let demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });
});



